<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Change Item</title>

    <style>
        html {
            margin: 0;
            padding: 0;
            height: 100%;
            background: url('img/background.png') no-repeat center center;
            background-size: 95%;
            background-color: #000;
            background-attachment: fixed;
            image-rendering: pixelated;
        }

        body {
            margin: 0;
            padding: 0;
            min-height: 100%;
        }

        #top {
            height: 50px;
            width: 100%;
            background-color: #000;
            display: flex;
            align-items: center; /* 垂直居中 */
            justify-content: space-between; /* 左右两端对齐 */
            padding: 0 10px;
            box-sizing: border-box;
        }

        #loge {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        #loge img {
            height: 40px;
            width: 40px;
            image-rendering: pixelated;
        }

        #loge p {
            color: #d1d1d1;
            font-size: 20px;
            margin: 0;
        }

        #login {
            height: 50px;
            display: flex;
            flex-direction: row;
            align-items: center;
        }

        #login p {
            color: #d1d1d1;
            font-size: 16px;
            margin: 0;
            user-select: none;
        }

        .operaButton {
            height: 30px;
            padding: 0 12px;
            background-color: #3a3a3a;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 10px;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.2s ease;
            box-sizing: border-box;
        }

        .operaButton:hover {
            background-color: #505050;
        }

        #title {
            width: 100%;
        }

        h1 {
            font-size: 36px;
            text-align: center;
            margin: 0 0 20px 0;
            color: #d1d1d1;
        }

        #content {
            margin: 0 auto;
            width: 75%;
            min-height: calc(100vh - 50px);
            background-color: #2c2925;
        }

        /* 表单整体样式 */
        #itemForm {
            max-width: 700px;
            margin: 0 auto;
        }

        /* 表单区域标题 */
        #itemForm h2 {
            text-align: center;
            margin: 20px 0 10px;
            color: #f0f0f0;
        }

        /* 表单内每行排版 */
        #itemForm div {
            display: flex;
            align-items: center;
            justify-content: center;
            flex-wrap: wrap;
            margin-bottom: 10px;
        }

        /* 标签样式 */
        #itemForm label {
            margin: 5px 8px;
            min-width: 100px;
            text-align: right;
        }

        /* 输入框、选择框统一风格 */
        #itemForm input[type="text"],
        #itemForm input[type="number"],
        #itemForm select,
        #itemForm textarea {
            background-color: #3a3a3a;
            color: #d1d1d1;
            border: 1px solid #555;
            border-radius: 4px;
            padding: 6px 10px;
            margin: 5px;
            outline: none;
        }

        #itemForm input[type="file"] {
            color: #d1d1d1;
        }

        /* 多选框道具池样式 */
        #itemPools {
            background-color: #3a3a3a;
            color: #d1d1d1;
            border: 1px solid #555;
            border-radius: 4px;
            padding: 5px;
            width: 100%;
            box-sizing: border-box;
        }

        /* 按钮样式 */
        #itemForm button {
            background-color: #505050;
            color: #d1d1d1;
            border: none;
            padding: 8px 14px;
            border-radius: 6px;
            cursor: pointer;
            margin: 5px;
        }

        #itemForm button:hover {
            background-color: #707070;
        }

        /* 协同列表样式 */
        #synergyList div {
            background-color: #3a3a3a;
            padding: 6px 10px;
            border-radius: 4px;
            margin: 5px 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        /* hr 分隔线美化 */
        #itemForm hr {
            border: 0;
            height: 1px;
            background: #444;
            margin: 20px 0;
        }

        /* 提交按钮单独样式 */
        #submitBtn {
            width: 200px;
            font-size: 18px;
            background-color: #707070;
            color: #f0f0f0;
            border: none;
            padding: 12px 0;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        #submitBtn:hover {
            background-color: #909090;
        }

        #deleteBtn {
            width: 200px;
            font-size: 18px;
            background-color: #c0392b !important; /* 红色 */
            color: #f0f0f0;
            border: none;
            padding: 12px 0;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        #deleteBtn:hover {
            background-color: #992d22 !important; /* 深红色 */
        }
    </style>
</head>
<body>
<div id="top">
    <div id="loge">
        <img src="img/site_avatar_isaac_l.webp" alt="Isaac Wiki">
        <p>以撒的结合Wiki</p>
    </div>
    <div id="login">
        <!-- 预留登录/注册区域 -->
    </div>
</div>
<div id="content">
    <div id="title">
        <h1>道具修改</h1>
    </div>
    <form id="itemForm" style="padding:20px; color:#d1d1d1;">

        <!-- 第一区域：道具基本信息 -->
        <h2>道具基本信息</h2>

        <div>
            <label>ID：</label>
            <input type="number" id="itemId" name="itemId" required readonly>
            <label>名称：</label>
            <input type="text" id="itemName" name="itemName" required>
        </div>
        <br>
        <div>
            <label>品质(0-4)：</label>
            <input type="number" id="quality" name="quality" min="0" max="4" required>
            <label>类型：</label>
            <select id="itemType" name="itemType" required>
                <option value="">请选择</option>
                <option value="1">主动道具</option>
                <option value="0">被动道具</option>
            </select>
        </div>
        <br>
        <div id="powerRow" style="display:none;">
            <label>充能：</label>
            <input type="number" id="power" name="power">
        </div>
        <br>
        <div>
            <label>效果：</label>
            <textarea id="effect" name="effect" rows="3" cols="50"></textarea>
        </div>

        <hr>

        <!-- 第二区域：道具属性 -->
        <h2>道具属性</h2>

        <div>
            <label>生命上限：</label>
            <input type="text" id="maxHp" name="maxHp">
            <label>生命恢复：</label>
            <input type="text" id="hp" name="hp">
        </div>
        <br>
        <div>
            <label>攻击力：</label>
            <input type="text" id="damage" name="damage">
            <label>射速：</label>
            <input type="text" id="tears" name="tears">
        </div>
        <br>
        <div>
            <label>攻击范围：</label>
            <input type="text" id="range" name="range">
            <label>弹速：</label>
            <input type="text" id="shotSpeed" name="shotSpeed">
        </div>
        <br>
        <div>
            <label>速度：</label>
            <input type="text" id="speed" name="speed">
            <label>幸运：</label>
            <input type="text" id="lucky" name="lucky">
        </div>
        <br>
        <div>
            <label>恶魔房开房率：</label>
            <input type="text" id="devilProbability" name="devilProbability">
            <label>天使房转化率：</label>
            <input type="text" id="angelProbability" name="angelProbability">
        </div>

        <hr>

        <!-- 第三区域：协同效应 -->
        <h2>协同效应</h2>
        <div>
            <label>协同道具ID：</label>
            <input type="number" id="synergyItemId">
            <label>协同效应：</label>
            <input type="text" id="synergyEffect">
            <button type="button" id="addSynergyBtn">添加</button>
        </div>
        <div id="synergyList" style="margin-top:10px;"></div>

        <hr>

        <!-- 道具池选择 -->
        <h2>道具池</h2>
        <select id="itemPools" multiple size="8">
            <option value="1">宝箱房</option>
            <option value="2">商店</option>
            <option value="3">头目房</option>
            <option value="4">恶魔房</option>
            <option value="5">天使房</option>
            <option value="6">隐藏房</option>
            <option value="7">图书馆</option>
            <option value="8">赌博乞丐</option>
            <option value="9">金箱子</option>
            <option value="10">红箱子</option>
            <option value="11">乞丐</option>
            <option value="12">恶魔乞丐</option>
            <option value="13">诅咒房</option>
            <option value="14">钥匙乞丐</option>
            <option value="15">电池乞丐</option>
            <option value="16">妈妈的箱子</option>
            <option value="17">夹娃娃机</option>
            <option value="18">究极隐藏房</option>
            <option value="19">星象房</option>
            <option value="20">旧箱子</option>
            <option value="21">宝宝商店</option>
            <option value="22">木箱子</option>
            <option value="23">腐烂乞丐</option>
        </select>

        <hr>

        <!-- 图片选择 -->
        <h2>图片</h2>
        <input type="file" id="itemImg" name="itemImg">

        <hr>

        <!-- 提交按钮 -->
        <div style="display: flex; justify-content: center; gap: 20px;">
            <button type="button" id="submitBtn">提交</button>
            <button type="button" id="deleteBtn">删除</button>
        </div>

    </form>
</div>
</body>

<script src="js/jQuery-3.7.1.min.js"></script>
<script>
    $(document).ready(function () {

        const jwt = localStorage.getItem("jwt");
        const loginDiv = $("#login");

        if (jwt) {
            // 有 jwt，显示头像、名称和登出按钮
            const name = localStorage.getItem("name") || "用户";
            const imgUrl = localStorage.getItem("imgUrl") || "img/default_avatar.png";

            const userHtml = `
    <img src="${imgUrl}" alt="头像" id="userAvatar" style="height:30px; width:30px; border-radius:50%; vertical-align:middle; margin-right:8px; object-fit:cover;">
    <p id="userName" style="color:#d1d1d1; font-size:16px; margin:0; line-height:30px; display:inline-block; vertical-align:middle;">${name}</p>
    <div id="logoutBtn" class="operaButton" style="margin-left:12px;">
        <p>登出</p>
    </div>
`;
            loginDiv.html(userHtml);

            // 登出按钮暂时不绑定事件，后续可以加
            $("#logoutBtn").click(() => {
                // 清除登录相关的 localStorage 信息
                localStorage.removeItem("jwt");
                localStorage.removeItem("name");
                localStorage.removeItem("imgUrl");
                // 你如果存了别的登录相关信息，也一起清理，比如 id、username 等等
                localStorage.removeItem("id");
                localStorage.removeItem("username");

                // 刷新页面
                location.reload();
            });

            // ✅ 绑定头像和用户名点击跳转 userInfo.html
            $("#userAvatar, #userName").click(() => {
                window.open("userInfo.html");
            });

        } else {
            // 未登录，提示并跳转
            alert("未登录，请先登录！");
            window.location.href = "ItemList.html";
        }

        function getQueryParam(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }

        const itemId = getQueryParam("id");
        if (!itemId) {
            alert("缺少道具ID！");
            window.location.href = "ItemList.html";
        }

        // 定义一个全局变量保存 createId
        let createId = null;

        $.ajax({
            url: "http://localhost:8080/QueryItemById",
            type: "GET",
            data: {id: itemId},
            dataType: "json",
            success: function (res) {
                if (res.code !== 1) {
                    alert("获取道具数据失败！");
                    return;
                }

                const data = res.data;
                const item = data.item;
                const attributes = data.itemsAttributes;
                const synergies = data.synergies;
                const pools = data.itemPoolTypes;
                const imgPath = data.itemImgPath;

                // 保存 createId
                createId = item.createId;

                // 基本信息
                $("#itemId").val(item.id);
                $("#itemName").val(item.name);
                $("#quality").val(item.quality);
                $("#itemType").val(item.type);
                $("#effect").val(item.effect);

                // 显示充能行（如果是主动道具）
                if (item.type === 1) {
                    $("#powerRow").show();
                    $("#power").val(item.power);
                }

                // 道具属性
                for (let key in attributes) {
                    if (attributes[key] !== null && key !== "id") {
                        $(`#${key}`).val(attributes[key]);
                    }
                }

                // 协同效应
                // 清空协同效应列表
                $("#synergyList").empty();

                synergies.forEach((syn, index) => {
                    const synergyHtml = `
        <div class="synergyItem" data-index="${index}" style="
            background-color: #3a3a3a;
            padding: 6px 10px;
            border-radius: 4px;
            margin: 5px 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        ">
            <span>ID${syn.itemBId}：${syn.effect}</span>
            <button type="button" class="removeSynergyBtn" style="
                background-color: #707070;
                color: #f0f0f0;
                border: none;
                margin-left: 10px;
                padding: 4px 8px;
                border-radius: 4px;
                cursor: pointer;
            ">删除</button>
        </div>
    `;
                    $("#synergyList").append(synergyHtml);
                });

// 删除按钮事件（用事件委托，避免后添加的按钮不生效）
                $("#synergyList").off("click").on("click", ".removeSynergyBtn", function () {
                    $(this).parent().remove();
                });

                // 道具池
                pools.forEach(pool => {
                    $(`#itemPools option[value='${pool.id}']`).prop("selected", true);
                });

                // 图片
                if (imgPath && imgPath.path) {
                    $("#itemImg").after(`
        <div style="margin-top:10px; text-align:center;">
            <img src="${imgPath.path.trim()}" alt="道具图片" style="
                width: 128px;
                height: 128px;
                image-rendering: pixelated;
                border: 2px solid #222;
                background-color: #1a1a1a;
                padding: 4px;
            ">
        </div>
    `);
                }
            },
            error: function () {
                alert("服务器连接失败！");
            }
        });

        // 页面加载时，初始化充能框显示状态
        function updatePowerRow() {
            if ($("#itemType").val() === "1") {
                $("#powerRow").show();
            } else {
                $("#powerRow").hide();
                $("#power").val("");
            }
        }

        updatePowerRow(); // 页面载入时执行一次

        // 监听道具类型改变
        $("#itemType").change(function () {
            updatePowerRow();
        });

        $("#deleteBtn").click(function () {
            const id = $("#itemId").val();
            const token = localStorage.getItem("jwt");
            if (!id) {
                alert("道具ID不存在，无法删除！");
                return;
            }
            if (!token) {
                alert("未登录或登录信息失效！");
                return;
            }

            if (!confirm("确定删除该道具吗？此操作不可撤销！")) {
                return;
            }

            $.ajax({
                url: "http://localhost:8080/user/deleteItem",
                type: "POST",
                data: { id: id },
                headers: {
                    "token": jwt
                },
                success: function(res) {
                    // 这里根据你的Result类格式判断成功
                    if (res.code === 1) {
                        alert("删除成功");
                        // 关闭当前页面
                        window.close();
                    } else {
                        alert("删除失败：" + (res.msg || "未知错误"));
                    }
                },
                error: function() {
                    alert("请求失败，无法删除");
                }
            });
        });

        // 添加协同效应
        $("#addSynergyBtn").click(function () {
            const synergyItemId = $("#synergyItemId").val().trim();
            const synergyEffect = $("#synergyEffect").val().trim();

            if (synergyItemId === "" || synergyEffect === "") {
                alert("请填写协同道具ID和协同效应！");
                return;
            }

            const index = $("#synergyList div").length; // 当前协同数量作为索引

            const synergyHtml = `
        <div class="synergyItem" data-index="${index}" style="
            background-color: #3a3a3a;
            padding: 6px 10px;
            border-radius: 4px;
            margin: 5px 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        ">
            <span>ID${synergyItemId}：${synergyEffect}</span>
            <button type="button" class="removeSynergyBtn" style="
                background-color: #707070;
                color: #f0f0f0;
                border: none;
                margin-left: 10px;
                padding: 4px 8px;
                border-radius: 4px;
                cursor: pointer;
            ">删除</button>
        </div>
    `;

            $("#synergyList").append(synergyHtml);

            // 清空输入框
            $("#synergyItemId").val("");
            $("#synergyEffect").val("");
        });

        // 小函数：空字符串转 null，其他照传
        function nullableVal(val) {
            return val === "" ? null : val;
        }

        $("#submitBtn").click(function () {
            const jwt = localStorage.getItem("jwt");
            const userId = localStorage.getItem("id");

            if (!jwt || !userId) {
                alert("未登录或登录信息失效！");
                return;
            }

            // 检查必填项
            if ($("#itemId").val() === "" || $("#itemName").val() === "" || $("#quality").val() === "" || $("#itemType").val() === "") {
                alert("请填写完整道具ID、名称、品质和类型！");
                return;
            }

            if ($("#itemType").val() === "1" && $("#power").val().trim() === "") {
                alert("主动道具的充能不能为空！");
                return;
            }

            // 上传图片（可为空）
            const fileInput = $("#itemImg")[0];
            const formData = new FormData();
            if (fileInput.files.length > 0) {
                formData.append("file", fileInput.files[0]);
            } else {
                formData.append("file", null);
            }

            $.ajax({
                url: "http://localhost:8080/user/updateItemImage",
                type: "POST",
                headers: {
                    "token": jwt
                },
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (res) {
                    if (res.code !== 1) {
                        alert("图片上传失败: " + res.msg);
                        return;
                    }

                    const imageUrl = res.data;

                    const itemId = Number($("#itemId").val());

                    // 道具池
                    const itemPools = [];
                    $("#itemPools option:selected").each(function () {
                        itemPools.push({
                            id: Number($(this).val()),
                            name: $(this).text()
                        });
                    });

                    // 协同效应
                    const synergies = [];
                    $("#synergyList div").each(function () {
                        const text = $(this).find("span").text();
                        const idMatch = text.match(/ID(\d+)/);
                        const effectMatch = text.match(/：(.+)/);
                        if (idMatch && effectMatch) {
                            synergies.push({
                                itemAId: itemId,
                                itemBId: Number(idMatch[1]),
                                effect: effectMatch[1].trim()
                            });
                        }
                    });

                    // 构建完整提交对象
                    const data = {
                        item: {
                            id: itemId,
                            name: $("#itemName").val(),
                            quality: Number($("#quality").val()),
                            type: Number($("#itemType").val()),
                            power: $("#power").val() === "" ? null : Number($("#power").val()),
                            effect: $("#effect").val() === "" ? null : $("#effect").val(),
                            createId: createId,      // 使用之前缓存的 createId
                            changeId: Number(userId)
                        },
                        itemsAttributes: {
                            id: itemId,
                            maxHp: nullableVal($("#maxHp").val()),
                            hp: nullableVal($("#hp").val()),
                            damage: nullableVal($("#damage").val()),
                            tears: nullableVal($("#tears").val()),
                            range: nullableVal($("#range").val()),
                            shotSpeed: nullableVal($("#shotSpeed").val()),
                            speed: nullableVal($("#speed").val()),
                            lucky: nullableVal($("#lucky").val()),
                            devilProbability: nullableVal($("#devilProbability").val()),
                            angelProbability: nullableVal($("#angelProbability").val())
                        },
                        synergies: synergies,
                        itemPoolTypes: itemPools,
                        itemImgPath: {
                            itemId: itemId,
                            path: imageUrl    // "no update" 或 图片路径
                        }
                    };

                    // 发起修改请求
                    $.ajax({
                        url: "http://localhost:8080/user/updateItem",
                        type: "POST",
                        headers: {
                            "token": jwt
                        },
                        contentType: "application/json",
                        data: JSON.stringify(data),
                        success: function (res) {
                            if (res.code === 1) {
                                alert("道具修改成功！");
                                window.location.href = "itemInfo.html?id=" + itemId;
                            } else {
                                alert("道具修改失败: " + res.msg);
                            }
                        },
                        error: function () {
                            alert("提交道具时发生错误！");
                        }
                    });
                },
                error: function () {
                    alert("上传图片失败！");
                }
            });
        });
    })
</script>
</html>